<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <select id="p">
        <option value="">请选择</option>
    </select>
    <select id="c">
        <option value="">请选择</option>
    </select>
    <script>
        //获取省份
        var p = document.querySelector("#p")
        //获取城市
        var c = document.querySelector("#c")
        /* 准备数据 */
        var province = ["江西", "湖南", "广东", "广西"]
        var city = [
            ["南昌", "九江", "萍乡", "赣州"],
            ["长沙", "株洲", "湘潭", "岳阳"],
            ["广州", "深圳", "东莞", "佛山"],
            ["南宁", "桂林", "柳州", "百色"]
        ]
        /* 
            1. 先将省渲染出来
                遍历省,每遍历一次,创建一个option,文本值为数组的元素
        */
        province.forEach(function (item, index) {
            //创建option
            var option = document.createElement("option")
            //给option添加文本值
            option.innerText = item
            //添加value值
            option.value = index;
            //将option追加到
            p.appendChild(option)
        })


        /* 2. 添加城市了 */
        p.onchange = function () {
            c.innerHTML = "<option value=''>请选择</option>"
            //遍历出来对应城市
            //获取省份的下标
            var index = this.value;
            //获取省份里面对应的城市
            // console.log(city[index]);
            var cityArr = city[index]
            cityArr.forEach(function(item,i){
                var cc = document.createElement("option")
                cc.innerHTML = item;
                cc.value = i;
                c.appendChild(cc)
            })
        }
    </script>
</body>

</html>